package com.zz.springboot.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 * <p>
 * 要考虑多线程下SimpleDateFormat的parse()和format()安全性
 */
@Slf4j
public class DateUtils {

    /**
     * 为了控制多线程下SimpleDateFormat的数据安全性
     **/
    private static ThreadLocal<Map<String, SimpleDateFormat>> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>());

    /**
     * 获得当前时间——String
     *
     * @param pattern
     * @return
     */
    public static String getCurrentTimeStr(String pattern) {
        /*------------------------单线程下，如下方式线程安全------------------------
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        return simpleDateFormat.format(date);
        ------------------------------------------------------------------------*/

        /**------------------------多线程下，如下方式线程安全------------------------**/
        Map<String, SimpleDateFormat> dateFormatMap = threadLocal.get();
        SimpleDateFormat simpleDateFormat = dateFormatMap.get(pattern);
        if (simpleDateFormat == null) {
            simpleDateFormat = new SimpleDateFormat(pattern);
            dateFormatMap.put(pattern, simpleDateFormat);
        }
        return simpleDateFormat.format(new Date());
    }

    /**
     * 获得当前时间——Date
     * @param pattern
     * @return
     */
    public static Date getCurrentTime(String pattern) {
        return parseTime(getCurrentTimeStr(pattern), pattern);
    }

    /**
     * 将String转换为Date
     * @param dateStr
     * @param pattern
     * @return
     */
    public static Date parseTime(String dateStr, String pattern) {
        if (!StringUtils.hasText(dateStr)) {
            return null;
        }
        Date date = null;
        try {
            date = org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, pattern);
        } catch (ParseException e) {
            log.error("------------------时间类型转换错误", e);
        }
        return date;
    }

    /**
     * Date 截取到年月日，返回 Date 类型
     * @param date
     * @return
     */
    public static Date truncateToYMD(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

}
